<?php
namespace Sdk\Fop;

class CallFopApiUtil
{
    const APP_KEY = 'dce43813-081c-4ba0-b255-659007247581';
    const VERSION = '1.0';
    const CONNECT_TIMEOUT = 120;
    const READ_TIMEOUT = 120;
    const FORMAT = 'json';
    const SERVICE_URL = 'http://open.4px.com/router/api/service';
    const APP_SECRET = 'dd65cb3e-2470-4390-978e-94528bcff3d8';

    //调用递四方接口入口
    public static function callFopApi($action, $data)
    {
        //请求参数先按键值升序进行排序
        ksort($data);
        $data = json_encode($data);
        $postData = self::buildSignData($action, $data);
        //请求接口获取数据
        ksort($postData);
        $response = self::postCurl($postData, $data);
        $responseArr = json_decode($response, true);
        return $responseArr;
    }


    //获取数据
    public static function postCurl($data, $param)
    {
        $url = self::SERVICE_URL . '?method='.$data['method'];
        unset($data['method']);
        $stringArr = [];
        foreach ($data as $k => $v) {
            $stringArr[] = "{$k}={$v}";
        }
        $url .= '&' . implode("&", $stringArr);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (self::CONNECT_TIMEOUT) {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::CONNECT_TIMEOUT);
        }
        if (self::READ_TIMEOUT) {
            curl_setopt($ch, CURLOPT_TIMEOUT, self::READ_TIMEOUT);
        }
        $response = curl_exec($ch);
        unset($data);
        try {
            if (curl_errno($ch)) {
                throw new \Exception(curl_error($ch), 0);
            } else {
                $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if ($httpStatusCode !== 200) {
                    throw new \Exception($response, $httpStatusCode);
                }
            }
        } finally {
            curl_close($ch);
        }

        return $response;
    }

    //获取签名
    public static function buildSignData($action, $data)
    {
        $postData = [
            'method' => $action
        ];
        $systemParam = self::getSystemParams();
        //把传入的值与公共的值进行合并后再调用签名，把签名的值一起再返回
        $postData = array_merge($systemParam, $postData);
        $postData['sign'] = self::generateSign($postData, $data);
        return $postData;
    }


    //公共参数签名
    private static function getSystemParams()
    {
        $systemParam = [
            'app_key' => self::APP_KEY,
            'format' => self::FORMAT,
            'timestamp' => self::getTimestamp(),
            'v' => self::VERSION
        ];
        return $systemParam;
    }

    //返回微秒
    private static function getTimestamp()
    {
        $time = explode (" ",microtime());
        $time = $time [1] . ($time [0] * 1000);
        $time2 = explode ( ".", $time );
        $time = $time2 [0];
        return $time;
    }

    //生成签名
    private static function generateSign($params, $data)
    {
        ksort($params);
        $stringToBeSigned = '';
        foreach ($params as $k => $v) {
            $stringToBeSigned .= "$k$v";
        }
        unset($k, $v);
        return strtolower(md5($stringToBeSigned . $data. self::APP_SECRET));
    }

}